package com.kingsoft.miot.bridge.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kingsoft.miot.bridge.common.CommonResult;

/**
 * 登录 拦截器
 * 
 * @author HUJIANQING
 *
 */
@Service
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoginInterceptor.class);

	/**
	 * 前置处理
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			// 获取请求的URI 去除过滤 http://localhost:8888 prefix
			String requestURI = request.getRequestURI();
			// 登录公开
			if (requestURI.indexOf("/login") >= 0) {
				return true;
			}
			// 获取session
			HttpSession session = request.getSession();
			Object data = session.getAttribute("mng_user_access");
			if (data != null && !StringUtils.isBlank(data.toString())) {
				return true;
			}
			// 设置返回数据
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			String returnJson = CommonResult.returnJson(false, 400, "请登录.");
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.append(returnJson);
				return false;
			} catch (Exception e) {
				LOGGER.error("拦截后返回数据失败！");
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

}
